#!/bin/sh
# Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# postrm script for omd
#
# see: dh_installdeb(1)

set -e

# summary of how this script can be called:
#        * <postrm> `remove'
#        * <postrm> `purge'
#        * <old-postrm> `upgrade' <new-version>
#        * <new-postrm> `failed-upgrade' <old-version>
#        * <new-postrm> `abort-install'
#        * <new-postrm> `abort-install' <old-version>
#        * <new-postrm> `abort-upgrade' <old-version>
#        * <disappearer's-postrm> `disappear' <overwriter>
#          <overwriter-version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

APACHE_OMD_CONF="/etc/apache2/conf.d/zzz_omd.conf"
APACHE_OMD_EMPTY_CONF="/opt/omd/apache/empty.conf"
OMD="omd-{CMK_VERSION}.{CMK_EDITION}"

case "$1" in
    upgrade)
    ;;

    remove|failed-upgrade|abort-install|abort-upgrade|disappear)
      # update-alternatives --remove  omd /omd/versions/{CMK_VERSION}.{CMK_EDITION}
    ;;

    purge)
      ALTERNATIVES=`update-alternatives --list omd 2>/dev/null | egrep -v 'No alternatives'` || /bin/true
      if [ -z "$ALTERNATIVES" ]; then
	  echo "Removing system group 'omd'"
	  groupdel omd || true
	  echo "Removing global links/directories"
	  # rm -f /usr/bin/omd # -> alternatives
	  # rm -f /usr/share/man/man8/omd.8.gz # -> alternatives
	  # rm -f /etc/init.d/omd # -> alternatives
	  rm -f /etc/default/omd
          if test -d /etc/apache2/conf-available; then
            # On e.g. ubuntu 13.10 conf.d is not used anymore, use conf-available
            APACHE_OMD_CONF="/etc/apache2/conf-available/zzz_omd.conf"
          fi
	  ! test -x /usr/sbin/a2disconf || a2disconf zzz_omd || true
	  rm -f $APACHE_OMD_CONF $APACHE_OMD_EMPTY_CONF
	  rm -f /omd
          if test -f /etc/systemd/system/omd.service; then
              rm -f /etc/systemd/system/omd.service
          fi
	  # Try to remove empty directories
	  if test -d /opt/omd/versions; then
	    rmdir --ignore-fail-on-non-empty /opt/omd/versions
	  fi
	  if test -d /opt/omd/sites; then
	    rmdir --ignore-fail-on-non-empty /opt/omd/sites
	  fi
	  if test -d /opt/omd/apache; then
	    rmdir --ignore-fail-on-non-empty /opt/omd/apache
	  fi
	  if test -d /opt/omd; then
	    rmdir --ignore-fail-on-non-empty /opt/omd
	  fi

      fi
    ;;

    *)
        echo "postrm called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
